using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;

namespace MimeCloud.Foundations.Helpers
{
    public static class WebHelper
    {
        public static string GetWebExceptionResponse(WebException ex)
        {
            string responseString = null;
            if (ex.Response != null)
            {
                responseString = new StreamReader((ex.Response as HttpWebResponse).GetResponseStream()).ReadToEnd();
            }            
            return responseString;
        }

        public static string ToQueryString(IDictionary<string, string> values, bool encodeParams)
        {
            string returnString = "";
            foreach (KeyValuePair<string, string> pair in values)
            {
                if (!string.IsNullOrEmpty(returnString))
                {
                    returnString += "&";
                }
                returnString += string.Format("{0}={1}", pair.Key, encodeParams ? HttpUtility.UrlEncode(pair.Value) : pair.Value);
            }
            return returnString;
        }

        public static IWebProxy GetDefaultProxy()
        {
            string proxyServer = String.Empty;
            string proxyUser = String.Empty;
            string proxyPass = String.Empty;
            proxyServer = ConfigurationManager.AppSettings.Get("WebProxy.Server");
            proxyUser = ConfigurationManager.AppSettings.Get("WebProxy.User");
            proxyPass = ConfigurationManager.AppSettings.Get("WebProxy.Pass");
            if (!String.IsNullOrEmpty(proxyServer))
            {
                WebProxy d = new WebProxy(proxyServer, 80);
                if (!String.IsNullOrEmpty(proxyUser))
                    d.Credentials = new NetworkCredential(proxyUser, proxyPass);
                return d;
            }
            else
            {
                IWebProxy result = WebRequest.DefaultWebProxy;
                result.Credentials = CredentialCache.DefaultCredentials;
                return result;
            }
        }
    }
}
